package com.atbeijing.D06;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

// 将迟到元素发送到侧输出流
public class Example6 {
    private static OutputTag<Tuple2<String, Long>> late = new OutputTag<Tuple2<String, Long>>("late"){};
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .addSource(new CustomSource())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Long>>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(r -> r.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sideOutputLateData(late)
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                        out.collect("窗口中有 " + elements.spliterator().getExactSizeIfKnown() + " 条元素");
                    }
                });

       // result.print();

        result.getSideOutput(late).print();


        env.execute();
    }

    public static class CustomSource implements SourceFunction<Tuple2<String, Long>> {
        @Override
        public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
            ctx.collect(Tuple2.of("a", 1000L));
            Thread.sleep(1000L);
            ctx.collect(Tuple2.of("a", 10 * 1000L));
            Thread.sleep(1000L);
            ctx.collect(Tuple2.of("a", 4000L));
        }

        @Override
        public void cancel() {

        }
    }
}
